package com.api.test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.bin.common.utils.StringUtils;

import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
//https://blog.csdn.net/weixin_45677145/article/details/104672151?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare
public class WuTestHttpClient {
	 public static String doGet(String url) {
	        CloseableHttpClient httpClient = null;
	        CloseableHttpResponse response = null;
	        String result = "";
	        try {
	            // 通过址默认配置创建一个httpClient实例
	            httpClient = HttpClients.createDefault();
	            // 创建httpGet远程连接实例
	            HttpGet httpGet = new HttpGet(url);
	            // 设置请求头信息，鉴权
	            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
	            // 设置配置请求参数
	            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
	                    .setConnectionRequestTimeout(35000)// 请求超时时间
	                    .setSocketTimeout(60000)// 数据读取超时时间
	                    .build();
	            // 为httpGet实例设置配置
	            httpGet.setConfig(requestConfig);
	            // 执行get请求得到返回对象
	            response = httpClient.execute(httpGet);
	            // 通过返回对象获取返回数据
	            HttpEntity entity = response.getEntity();
	            // 通过EntityUtils中的toString方法将结果转换为字符串
	            result = EntityUtils.toString(entity);
	            System.out.println("返回值 "+result);
	        } catch (ClientProtocolException e) {
	          System.out.println("连接异常:"+e.getMessage());
	        } catch (IOException e) {
	            System.out.println("IO异常"+e.getMessage());
	        } finally {
	            // 关闭资源
	            if (null != response) {
	                try {
	                    response.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return result;
	    }
	
	 
	 public static String doPost(String url, Map<String, Object> paramMap) {
	        CloseableHttpClient httpClient = null;
	        CloseableHttpResponse httpResponse = null;
	        String result = "";
	        // 创建httpClient实例
	        httpClient = HttpClients.createDefault();
	        // 创建httpPost远程连接实例
	        HttpPost httpPost = new HttpPost(url);
	        // 配置请求参数实例
	        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
	                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
	                .setSocketTimeout(60000)// 设置读取数据连接超时时间
	                .build();
	        // 为httpPost实例设置配置
	        httpPost.setConfig(requestConfig);
	        // 设置请求头
	        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//	        httpPost.addHeader("token", paramMap.get("token").toString());//如果需要token 应该是这样带上token信息吗?   
	        // 封装post请求参数
	        if (null != paramMap && paramMap.size() > 0) {
	            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	            // 通过map集成entrySet方法获取entity
	            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
	            // 循环遍历，获取迭代器
	            Iterator<Entry<String, Object>> iterator = entrySet.iterator();
	            while(iterator.hasNext()) {
	                Entry<String, Object> mapEntry = iterator.next();
	                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
	            }
	            
	            // 为httpPost设置封装好的请求参数
	            try {
	                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
	            } catch (UnsupportedEncodingException e) {
	                e.printStackTrace();
	            }
	        }
	        try {
	            // httpClient对象执行post请求,并返回响应参数对象
	            httpResponse = httpClient.execute(httpPost);
	            // 从响应对象中获取响应内容
	            HttpEntity entity = httpResponse.getEntity();
	            result = EntityUtils.toString(entity);
	            
	            
	            System.out.println("post请求返回结果: "+result);
//	            System.out.println("post请求返回结果entity.getContent()== "+entity.getContent());
	            JSONObject jsonObject = JSONObject.parseObject(result);
	            String CC = jsonObject.getString("AAA");
	            
	            System.out.println("post请求返回结果 建AAA== "+CC);
	            System.out.println("jsonObject== "+jsonObject);
	            
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            // 关闭资源
	            if (null != httpResponse) {
	                try {
	                    httpResponse.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return result;
	    }
	 public static CloseableHttpClient createSSLClientDefault() {
	        try {
	            //使用 loadTrustMaterial() 方法实现一个信任策略，信任所有证书
	            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
	                // 信任所有
	                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	                    return true;
	                }

	            }).build();
	            //NoopHostnameVerifier类:  作为主机名验证工具，实质上关闭了主机名验证，它接受任何
	            //有效的SSL会话并匹配到目标主机。
	            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
	            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
	            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
	        } catch (KeyManagementException e) {
	            e.printStackTrace();
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (KeyStoreException e) {
	            e.printStackTrace();
	        }
//	        return HttpClients.createDefault();
	        return null;
	    }
	 
	 public static String doPostByJson(String url,String json) {
		 CloseableHttpClient httpClient = null;
	        CloseableHttpResponse httpResponse = null;
	        String result = "";
	        // 创建httpClient实例     这是http请求连接客户端对象
//	        httpClient = HttpClients.createDefault();
	        
	        //这是https请求连接客户端对象
	        httpClient = createSSLClientDefault();
	        
	        
	        // 创建httpPost远程连接实例
	        HttpPost httpPost = new HttpPost(url);
	        // 配置请求参数实例
	        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间
	                .setConnectionRequestTimeout(35000)// 设置连接请求超时时间
	                .setSocketTimeout(60000)// 设置读取数据连接超时时间
	                .build();
	        // 为httpPost实例设置配置
	        httpPost.setConfig(requestConfig);
	        // 设置请求头
	        httpPost.addHeader("Content-Type", "application/json");
//	        httpPost.addHeader("token", paramMap.get("token").toString());//如果需要token 应该是这样带上token信息吗?   
	        
	        if(!StringUtils.isEmpty(json)) {
	        	StringEntity s;
				try {
					s = new StringEntity(json.toString());
					s.setContentEncoding("UTF-8");
//		            s.setContentType("application/json");//发送json数据需要设置contentType
			        httpPost.setEntity(s);
				} catch (UnsupportedEncodingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	        }
	        
	        
	        try {
	            // httpClient对象执行post请求,并返回响应参数对象
	            httpResponse = httpClient.execute(httpPost);
	            
	            // 从响应对象中获取响应内容
	            HttpEntity entity = httpResponse.getEntity();
	            
	            result = EntityUtils.toString(entity,"utf-8");
	            return result;
	            		
	            
	            
//	            System.out.println("post请求返回结果entity.getContent()== "+entity.getContent());
//	            JSONObject jsonObject = JSONObject.parseObject(result);
//	            String CC = jsonObject.getString("XXX");
//	            
//	            System.out.println("post请求返回结果 建XXX== "+CC);
//	            System.out.println("jsonObject== "+jsonObject);
//	            Object date = jsonObject.getString("date");
//	            System.out.println("请求返回结果  对象: == "+date.toString());
	            
//	            if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {
//	            	  // 从响应对象中获取响应内容i
//		            HttpEntity entity = httpResponse.getEntity();
//		            result = EntityUtils.toString(entity);
//		            System.out.println("post请求返回结果: "+result);
////		            System.out.println("post请求返回结果entity.getContent()== "+entity.getContent());
//		            JSONObject jsonObject = JSONObject.parseObject(result);
//		            String CC = jsonObject.getString("AAA");
//		            
//		            System.out.println("post请求返回结果 建AAA== "+CC);
//		            System.out.println("jsonObject== "+jsonObject);
//	            }else {
//	            	System.out.println("返回失败"+httpResponse.getStatusLine().getStatusCode());
//	            }
	          
	            
	        } catch (ClientProtocolException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            // 关闭资源
	            if (null != httpResponse) {
	                try {
	                    httpResponse.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (null != httpClient) {
	                try {
	                    httpClient.close();
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	        return result;
	    }
	//非对称密钥创建,,,返回秘钥标识keyCode
		public static String createKey() {
			//测试 https://10.150.84.219:15443      https://10.147.59.198:15443  这个是生产环境的。
			
//			/api/v1/kms/dek/createKeyPair 
			String IP = "https://10.150.84.219:15443/api/v1/kms/dek/createKeyPair";
			
			//请求参数
	    	Map<String, Object> map = new HashMap<String, Object>();
			map.put("algorithm", "SM2");//密钥算法	
			map.put("length", 256);//length	number	是	密钥长度	SM2长度：256
			map.put("period",365*1000);//有效期 单位天
			map.put("keyUsages","0");//0=加解密
			
			String jsonString = JSONObject.toJSONString(map);
	    	String createKeyResult = doPostByJson(IP,jsonString);
	    	if(createKeyResult != "") {
	    		  System.out.println("非对称密钥创建 post请求返回结果:jsonObject字符串    "+createKeyResult);
		            JSONObject jsonObject = JSONObject.parseObject(createKeyResult);
		            String message = jsonObject.getString("message");
		            String code = jsonObject.getString("code");//0=成功
		            Object obj = jsonObject.getString("date");
		            System.out.println("非对称密钥创建 post请求返回结果 date 对象== "+obj);
		            System.out.println("非对称密钥创建 post请求返回结果  对象== "+obj.toString());
		            
		            JSONObject jsonObject2 = JSONObject.parseObject(obj.toString());
		            System.out.println("  非对称密钥创建返回  keyCode  == "+jsonObject2.getString("keyCode"));
		            System.out.println("  非对称密钥创建返回 到期时间expirationTime  == "+jsonObject2.getString("expirationTime"));
		            return jsonObject2.getString("keyCode");
	    	}
	    	return "";
		}
		
		//通过非对称密钥创建接口返回的keyCode密钥标识  获取公钥
		public static String getKeyPair(String keyCode) {
			//测试 https://10.150.84.219:15443      https://10.147.59.198:15443  这个是生产环境的。
			String IP = "https://10.150.84.219:15443/api/v1/kms/dek/getPublicKey";
			
			//请求参数
	    	Map<String, Object> map = new HashMap<String, Object>();
			map.put("keyCode", keyCode);
			
			String jsonString = JSONObject.toJSONString(map);
	    	String createKeyResult = doPostByJson(IP,jsonString);
	    	if(createKeyResult != "") {
	    		  System.out.println(" 获取公钥  post请求返回结果:jsonObject字符串    "+createKeyResult);
		            JSONObject jsonObject = JSONObject.parseObject(createKeyResult);
		            String message = jsonObject.getString("message");
		            String code = jsonObject.getString("code");//0=成功
		            Object obj = jsonObject.getString("date");
		            System.out.println(" 获取公钥  post请求返回结果  对象== "+obj);
		            System.out.println(" 获取公钥 post请求返回结果  对象== "+obj.toString());
		            
		            JSONObject jsonObject2 = JSONObject.parseObject(obj.toString());
		            System.out.println("  公钥明文publicKey  ==  "+jsonObject2.getString("publicKey"));//公钥明文[BASE64]
		            return code;
	    	}
	    	return "";
		}
	 
	public static void main(String[] args) {
		
		String keyCode = createKey();//密钥标识  非对称密钥创建返回  keyCode密钥标识
		 getKeyPair( keyCode);//通过keyCode密钥标识 ,  获取非对称密钥对
		
		
//		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("test", "99999");
//		map.put("username", "wpn");
//		map.put("password", "123456");
//		
////		class We{
////			public String name="少的地方";
////		}
////		map.put("EE", new We());
//		
//		String jsonString = JSONObject.toJSONString(map);
//		System.out.println("发送出去的   "+jsonString);
//		String result = WuTestHttpClient.doPostByJson("https://localhost:8080/login/testwpn92",jsonString);
//		System.out.println("result = "+result);
//		
		
		
		
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("test", "99999");
//		map.put("username", "wpn");
//		map.put("password", "123456");
////		JSONObject jsonObject = JSONObject.parseObject(map.toString());
//		String jsonString = JSONObject.toJSONString(map);
//		WuTest.doPost("http://localhost:8080/loginGAI/testwpn", map);//  /login/*这样的不会被拦截/*  这
		
	}

}
